package com.dhecp.common.utils.log;

import com.dhecp.common.annotation.ForUpdate;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @program: kjecp
 * @description: 日志类
 * @author: hlf
 * @create: 2022-09-08 20:13
 */
public class BeanLogUtils {


    /**
     * 获取变更内容
     * @param newBean 更改前的Bean
     * @param oldBean 更改后的Bean
     * @param <T>
     * @return
     */
    public static <T> String getChangedFields(T newBean, T oldBean){
        Field[] fields = newBean.getClass().getDeclaredFields();
        StringBuilder builder = new StringBuilder();
        for(Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(ForUpdate.class)) {
                try {
                    Object newValue = field.get(newBean);
                    Object oldValue = field.get(oldBean);
                    if(!Objects.equals(newValue, oldValue)) {
                        builder.append(field.getAnnotation(ForUpdate.class).fieldName()); //获取字段名称
                        builder.append(": 【更改前：");
                        builder.append(newValue);
                        builder.append(", 更改后：");
                        builder.append(oldValue);
                        builder.append("】\n");
                    }
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
        return builder.toString();
    }
}